<?php

namespace App\Services\GoldStormSupport;

use App\Models\User;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class GoldStormSupportRequest extends FormRequest
{
	protected $child;

	public function rules()
	{
		if (!$this->user()->pay_code) {
			fail('请先设置交易密码');
		}

		return [
			'invite_code' => [
				'required', 'string',
				'min:10','max:10',
				'exists:users',
				$this->inviteCode(),
			],
			'pay_code' => $this->paycode(false)
		];
	}

	public function inviteCode()
	{
		return function ($key, $value, $fail) {

			/**
			 * @var User $user
			 */
			$user = $this->user();
			$child = User::where('invite_code', $value)->first();

			if (! $child) {
				return $fail('目标用户不存在');
			} elseif ($child->id == $user->id) {
				return $fail('仅可扶持下级');
			} elseif (empty($child->parent_id)) {
				return $fail('仅可扶持下级');
			} elseif ($child->id < $child->parent->id) {
				return $fail('仅可扶持下级');
			} elseif ($child->id < $user->id) {
				return $fail('仅可扶持下级');
			} elseif ($child->parent_id == $user->parent_id) {
				return $fail('仅可扶持下级');
			} elseif ($child->parent_id != $user->id) {
				return $fail('仅可扶持直属下级');
			} elseif ($child->hadGoldSupport()) {
				return $fail('每位下级仅可接受一次扶持');
			} else {
				$this->child = $child;
				return true;
			}
		};
	}

	public function getChild()
	{
		return $this->child;
	}
}
